﻿using System.Data;

namespace Swimj.DataCore;

public class Query
{
    private readonly IProvider _provider;

    private string _sqlPage = string.Empty;
    private string _sqlCount = string.Empty;

    public string SqlPage => _sqlPage;
    public string SqCount => _sqlCount;

    public Query(IProvider provider)
    {
        _provider = provider;
    }

    public Query(IDbConnection dbConnection)
    {
        var providerName = dbConnection.GetType().Module.Name;

        _provider = DatabaseProvider.Resolve(providerName, false);
    }

    public void BuildPageQueries(long page, long itemsPerPage, string sql)
    {
        // Split the SQL
        SqlParts parts;
        if (!_provider.PagingUtility.SplitSql(sql, out parts))
            throw new Exception("Unable to parse SQL statement for paged query");

        _sqlPage = _provider.BuildPageQuery((page - 1) * itemsPerPage, itemsPerPage, parts);
        _sqlCount = parts.SqlCount;
    }
}